import type { BuildOptions } from 'vite';

type $PreRenderedAsset = {
  name: string | undefined;
  source: Uint8Array | string;
  type: 'asset';
};

/**
 * 自定义底层的 Rollup 打包配置
 */
export function rollupOption(): BuildOptions['rollupOptions'] {
  return {
    output: {
      // 拆分代码
      manualChunks: {
        'vue': ['vue', 'vue-router'],
        'store': ['pinia', 'pinia-plugin-persistedstate'],
        'element-plus': ['element-plus'],
        'echarts': ['echarts'],
      },
      chunkFileNames: 'js/[name]-[hash].js',
      entryFileNames: 'js/[name]-[hash].js',
      // assetFileNames: '[ext]/[name]-[hash].[ext]',
      assetFileNames: (assetInfo: $PreRenderedAsset) => {
        const ext: string = assetInfo.name?.split('.').pop() || '';
        let extType: string = ext;
        if (['mp4', 'webm', 'ogg', 'mp3', 'wav', 'flac', 'aac'].includes(ext)) {
          extType = 'media';
        } else if (['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico'].includes(ext)) {
          extType = 'images';
        } else if (['woff', 'woff2', 'ttf', 'eot', 'otf'].includes(ext)) {
          extType = 'fonts';
        } else if (ext === 'css') {
          extType = 'css';
        } else {
          extType = 'assets';
        }
        return `${extType}/[name]-[hash].[ext]`;
      },
    },
  };
}
